#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('service:server');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '4000');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.Server(app);

const io=require('socket.io')(server);

// --------------- websocket code start ----------------------------

//在线用户
var onlineUser={};
var onlineCount=0;

io.on('connection',function (socket) {
  console.log('新用户登录');

  //监听新用户加入
  socket.on('login',function (obj) {
    socket.name=obj.userid;
    //检查用户在线列表
    if(!onlineUser.hasOwnProperty(obj.userid)){
      onlineUser[obj.userid]=obj.username;
      //在线人数+1
      onlineCount++;
    }
    //广播消息
    io.emit('login',{onlineUser:onlineUser,onlineCount:onlineCount,user:obj});
    console.log(obj.username+"加入了聊天室");
  });

  //监听用户退出
  socket.on('disconnect',function () {
    //将退出用户在在线列表删除
    if(onlineUser.hasOwnProperty(socket.name)){
      //退出用户信息
      var obj={userid:socket.name, username:onlineUser[socket.name]};
      //删除
      delete onlineUser[socket.name];
      //在线人数-1
      onlineCount--;
      //广播消息
      io.emit('logout',{onlineUser:onlineUser,onlineCount:onlineCount,user:obj});
      console.log(obj.username+"退出了聊天室");
    }
  });

  //监听用户发布聊天内容
  socket.on('message', function(obj){
    //向所有客户端广播发布的消息
    io.emit('message', obj);
    console.log(obj.username+'说：'+obj.content);
  });
});

// --------------- websocket code end ----------------------------

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
  console.log(`服务启动成功:${port}`);
}
